package org.tote.dao.util;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

public final class DaoUtils {

	public static final char QUOTE = '\'';

	private DaoUtils() {
	}

	/**
	 * Generates comma-separated list of ID's from List<T>
	 * 
	 * @param idList
	 *            - list of ID's in Long type
	 * @return - list of ID's in String
	 */

	public static <T> String generateIdList(List<T> idList) {
		if (idList.size() == 0) {
			return "('')";
		} else if (idList.size() == 1) {
			if (idList.get(0).toString().equals("")) {
				return "('')";
			}
		}
		StringBuilder idString = new StringBuilder("(");

		for (T id : idList) {
			idString.append(ensafe(id)).append(",");
		}
		// Removing last comma
		int commaIndex = idString.lastIndexOf(",");
		if (commaIndex > 0) {
			idString.deleteCharAt(commaIndex);
		}

		idString.append(")");

		return idString.toString();
	}

	private static HashSet<Character> needEnsafety = new HashSet<Character>() {
		private static final long serialVersionUID = 3807550231169233315L;
		{
			add('\"');
			add('\\');
			add('\'');
		}
	};

	public static <T> String ensafe(T value) {
		if (value instanceof Long) {
			return value.toString();
		}
		String beforeEnsafe = value.toString();
		StringBuilder ensafed = new StringBuilder();
		int start = 0, capacity = beforeEnsafe.length();
		if (beforeEnsafe.charAt(0) == QUOTE
				&& beforeEnsafe.charAt(beforeEnsafe.length() - 1) == QUOTE) {
			start++;
			capacity--;
		}
		ensafed.append(QUOTE);
		for (int i = start; i < capacity; i++) {
			if (needEnsafety.contains(beforeEnsafe.charAt(i))) {
				ensafed.append('\\');
			}
			ensafed.append(beforeEnsafe.charAt(i));
		}
		ensafed.append(QUOTE);
		return ensafed.toString();
	}

	public static List<Long> convertBigIntegerToLong(List<BigInteger> list) {
		List<Long> result = new ArrayList<Long>();
		for (BigInteger value : list) {
			result.add(((BigInteger) value).longValue());
		}
		return result;
	}
}